<template>
	<view class="schedule-viewer-container">
		
		<!-- 数据为空的提示 -->
		<view v-if="!scheduleData || !scheduleData.matches || scheduleData.matches.length === 0" class="empty-state">
			<view class="empty-icon">📋</view>
			<view class="empty-title">暂无选派数据</view>
			<view class="empty-desc">
				<text v-if="!scheduleData">数据加载失败，请稍后重试</text>
				<text v-else>该时段暂无选派记录</text>
			</view>
		</view>
		
		<!-- 比赛基本信息 -->
		<view v-else-if="scheduleData" class="match-info-section">
			<view class="info-row">
				<text class="info-label">系列赛名称：</text>
				<text class="info-value">{{ scheduleData.series_title }}</text>
			</view>
			<view class="info-row">
				<text class="info-label">查看时间：</text>
				<text class="info-value">{{ formatDateTime(new Date()) }}</text>
			</view>
			<view class="info-row">
				<text class="info-label">总计：</text>
				<text class="info-value">{{ scheduleData.total_matches }}场比赛，{{ scheduleData.total_selected }}人次</text>
			</view>
		</view>

		<!-- 比赛安排时间轴 -->
		<view v-if="scheduleData && scheduleData.matches && scheduleData.matches.length > 0" class="match-schedule-timeline">
			<view class="timeline-container">
				<view v-for="(dayGroup, dateKey) in groupedMatches" :key="dateKey" class="timeline-day">
					<!-- 日期标题 -->
					<view class="date-header">
						<text class="date-text">{{ formatTableDate(dateKey) }} 星期{{ getWeekday(dateKey) }}</text>
					</view>
					
					<!-- 该日期下的所有比赛 -->
					<view v-for="(match, index) in dayGroup" :key="index" class="time-slot-card">
						<view class="match-header">
							<text class="teams">{{ match.home_team }} vs {{ match.away_team }}</text>
							<text class="venue-info">【{{ match.venue }}】</text>
						</view>
						
						<view class="time-info">
							<text class="time-range">{{ match.time_range }}</text>
						</view>
						
						<!-- 裁判安排 -->
						<view class="referee-assignments">
							<view v-if="match.main_referee && match.main_referee !== '-'" class="referee-item" :class="{ 'highlight-user': isCurrentUser(match.main_referee) }">
								<text class="referee-name">{{ match.main_referee }}</text>
								<text class="referee-position">(主裁判)</text>
								<view v-if="match.main_referee_phone" class="phone-container">
									<text class="referee-phone">{{ match.main_referee_phone }}</text>
								</view>
							</view>
							<view v-if="match.assistant_referee && match.assistant_referee !== '-'" class="referee-item" :class="{ 'highlight-user': isCurrentUser(match.assistant_referee) }">
								<text class="referee-name">{{ match.assistant_referee }}</text>
								<text class="referee-position">(助理裁判)</text>
								<view v-if="match.assistant_referee_phone" class="phone-container">
									<text class="referee-phone">{{ match.assistant_referee_phone }}</text>
								</view>
							</view>
							<view v-if="match.fourth_official && match.fourth_official !== '-'" class="referee-item" :class="{ 'highlight-user': isCurrentUser(match.fourth_official) }">
								<text class="referee-name">{{ match.fourth_official }}</text>
								<text class="referee-position">(第四官员)</text>
								<view v-if="match.fourth_official_phone" class="phone-container">
									<text class="referee-phone">{{ match.fourth_official_phone }}</text>
								</view>
							</view>
							<view v-if="match.referee_supervisor && match.referee_supervisor !== '-'" class="referee-item" :class="{ 'highlight-user': isCurrentUser(match.referee_supervisor) }">
								<text class="referee-name">{{ match.referee_supervisor }}</text>
								<text class="referee-position">(裁判监督)</text>
								<view v-if="match.referee_supervisor_phone" class="phone-container">
									<text class="referee-phone">{{ match.referee_supervisor_phone }}</text>
								</view>
							</view>
							
							<!-- 等待选派提示 -->
							<view v-if="!hasAnyReferee(match)" class="waiting-assignment">
								<text class="waiting-text">等待选派...</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 底部操作区域 -->
		<view class="bottom-actions">
			<button class="action-btn back-btn" @click="goBack">返回</button>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			scheduleData: null,
			viewerRole: 'referee',
			highlightUserId: '',
			currentUserName: ''
		}
	},
	
	computed: {
		// 按日期分组的比赛数据
		groupedMatches() {
			if (!this.scheduleData || !this.scheduleData.matches) {
				return {}
			}
			
			const grouped = {}
			this.scheduleData.matches.forEach(match => {
				const date = match.date
				if (!grouped[date]) {
					grouped[date] = []
				}
				grouped[date].push(match)
			})
			
			// 按时间排序每天的比赛
			Object.keys(grouped).forEach(date => {
				grouped[date].sort((a, b) => {
					return a.time_range.localeCompare(b.time_range)
				})
			})
			
			return grouped
		}
	},
	
	onLoad(options) {
		this.initPage(options)
	},
	
	methods: {
		// 初始化页面
		async initPage(options) {
			try {
				console.log('schedule-viewer 初始化，options:', options);
				
				// 从本地存储读取数据
				if (options.key) {
					this.scheduleData = uni.getStorageSync(options.key);
					console.log('从本地存储读取数据，key:', options.key);
					console.log('读取到的数据:', this.scheduleData);
					// 读取后清除存储，避免占用空间
					uni.removeStorageSync(options.key);
				} else if (options.data) {
					// 兼容旧的传参方式
					this.scheduleData = JSON.parse(decodeURIComponent(options.data));
					console.log('从URL参数读取数据:', this.scheduleData);
				} else if (options.sessionId) {
					// 通过sessionId直接获取选派表数据
					console.log('通过sessionId获取数据:', options.sessionId);
					await this.loadScheduleDataBySessionId(options.sessionId, options);
				} else {
					console.log('没有找到数据源');
				}
				
				this.viewerRole = options.role || 'referee';
				this.highlightUserId = options.highlightUser || '';
				
				// 获取当前用户信息
				const userInfoStr = uni.getStorageSync('userInfo');
				if (userInfoStr) {
					const userInfo = JSON.parse(userInfoStr);
					this.currentUserName = userInfo.name || userInfo.username || '';
				}
				
				console.log('选派表数据最终结果:', this.scheduleData);
				console.log('当前用户:', this.currentUserName);
				console.log('查看者角色:', this.viewerRole);
				console.log('高亮用户ID:', this.highlightUserId);
				
			} catch (error) {
				console.error('初始化页面失败:', error);
				uni.showToast({
					title: '数据解析失败',
					icon: 'none'
				});
			}
		},
		
		// 通过sessionId加载选派表数据
		async loadScheduleDataBySessionId(sessionId, options) {
			try {
				uni.showLoading({ title: '加载选派表...' });
				
				console.log('loadScheduleDataBySessionId 开始，sessionId:', sessionId);
				console.log('options:', options);
				
				// 获取当前用户信息
				const userInfoStr = uni.getStorageSync('userInfo');
				if (!userInfoStr) {
					throw new Error('用户信息不存在');
				}
				const userInfo = JSON.parse(userInfoStr);
				
				// 调用云对象获取选派表数据
				const matchScheduleObject = uniCloud.importObject('match-schedule-object');
				
				const queryParams = {
					sessionIds: [sessionId],
					viewerRole: options.role || 'referee',
					viewerId: userInfo._id,
					onlyConfirmed: options.viewMode === 'confirmed' // 根据viewMode决定是否只查看已确认的
				};
				
				console.log('云对象查询参数:', queryParams);
				
				const result = await matchScheduleObject.getRoundSelectionSummary(queryParams);
				
				console.log('云对象查询结果:', result);
				uni.hideLoading();
				
				if (result.code === 0) {
					if (!result.data || !result.data.matches || result.data.matches.length === 0) {
						console.log('选派表数据为空');
						this.scheduleData = null;
						uni.showModal({
							title: '提示',
							content: '未找到对应的选派数据，可能数据还未生成或权限不足。',
							showCancel: false,
							confirmText: '我知道了'
						});
						return;
					}
					
					this.scheduleData = result.data;
					console.log('成功加载选派表数据:', this.scheduleData);
				} else {
					console.error('获取选派表失败:', result.message);
					this.scheduleData = null;
					uni.showToast({
						title: result.message || '获取选派表失败',
						icon: 'none'
					});
				}
			} catch (error) {
				uni.hideLoading();
				console.error('加载选派表数据异常:', error);
				this.scheduleData = null;
				uni.showToast({
					title: '加载选派表失败: ' + (error.message || '网络错误'),
					icon: 'none'
				});
			}
		},
		
		// 判断是否为当前用户
		isCurrentUser(refereeName) {
			return this.currentUserName && refereeName === this.currentUserName
		},
		
		// 检查是否有任何裁判
		hasAnyReferee(match) {
			return (match.main_referee && match.main_referee !== '-') ||
				   (match.assistant_referee && match.assistant_referee !== '-') ||
				   (match.fourth_official && match.fourth_official !== '-') ||
				   (match.referee_supervisor && match.referee_supervisor !== '-')
		},
		
		// 格式化表格日期
		formatTableDate(date) {
			if (!date) return ''
			const d = new Date(date)
			const month = String(d.getMonth() + 1).padStart(2, '0')
			const day = String(d.getDate()).padStart(2, '0')
			return `${month}月${day}日`
		},

		// 获取星期几
		getWeekday(date) {
			if (!date) return ''
			const d = new Date(date)
			const weekdays = ['日', '一', '二', '三', '四', '五', '六']
			return weekdays[d.getDay()]
		},
		
		// 格式化日期时间
		formatDateTime(date) {
			if (!date) return ''
			const d = new Date(date)
			const month = String(d.getMonth() + 1).padStart(2, '0')
			const day = String(d.getDate()).padStart(2, '0')
			const hour = String(d.getHours()).padStart(2, '0')
			const minute = String(d.getMinutes()).padStart(2, '0')
			return `${month}-${day} ${hour}:${minute}`
		},
		
		// 返回上一页
		goBack() {
			uni.navigateBack()
		}
	}
}
</script>

<style lang="scss" scoped>
.schedule-viewer-container {
	min-height: 100vh;
	background-color: #f5f5f5;
	padding-bottom: 120rpx;
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 120rpx 40rpx;
	text-align: center;
	
	.empty-icon {
		font-size: 80rpx;
		margin-bottom: 30rpx;
		opacity: 0.6;
	}
	
	.empty-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #666;
		margin-bottom: 16rpx;
	}
	
	.empty-desc {
		font-size: 28rpx;
		color: #999;
		line-height: 1.5;
	}
}

.page-header {
	background: linear-gradient(45deg, #1BAE76, #52c41a);
	padding: 40rpx 30rpx;
	text-align: center;
	
	.page-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #fff;
		text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
	}
}

.match-info-section {
	margin: 20rpx;
	padding: 24rpx;
	background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
	border-radius: 12rpx;
	border: 1rpx solid #e0e0e0;

	.info-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16rpx;
		padding: 8rpx 0;
		
		&:last-child {
			margin-bottom: 0;
		}

		.info-label {
			font-size: 28rpx;
			color: #666;
			font-weight: 500;
		}

		.info-value {
			font-size: 26rpx;
			color: #333;
			font-weight: 500;
			text-align: right;
		}
	}
}

.match-schedule-timeline {
	max-height: none;
	margin: 20rpx;
	
	.timeline-container {
		position: relative;
		
		.timeline-day {
			margin-bottom: 40rpx;
			position: relative;
			
			&:last-child {
				margin-bottom: 0;
			}
			
			&:not(:last-child)::after {
				content: '';
				position: absolute;
				left: 50rpx;
				top: 100%;
				width: 2rpx;
				height: 40rpx;
				background: linear-gradient(to bottom, #1BAE76, transparent);
			}
			
			.date-header {
				display: flex;
				align-items: center;
				margin-bottom: 20rpx;
				position: relative;
				
				&::before {
					content: '';
					position: absolute;
					left: 44rpx;
					top: 50%;
					transform: translateY(-50%);
					width: 12rpx;
					height: 12rpx;
					border-radius: 50%;
					background-color: #1BAE76;
					border: 3rpx solid #fff;
					box-shadow: 0 0 0 2rpx #1BAE76;
				}
				
				.date-text {
					font-size: 28rpx;
					font-weight: bold;
					margin-left: 80rpx;
					padding: 8rpx 16rpx;
					background: linear-gradient(45deg, #1BAE76, #52c41a);
					color: #fff;
					border-radius: 20rpx;
					box-shadow: 0 2rpx 8rpx rgba(27, 174, 118, 0.3);
				}
			}
			
			.time-slot-card {
				background-color: #fff;
				border-radius: 16rpx;
				padding: 20rpx;
				margin-left: 80rpx;
				margin-bottom: 16rpx;
				box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
				border: 1rpx solid #e8e8e8;
				position: relative;
				
				&:last-child {
					margin-bottom: 0;
				}
				
				&::before {
					content: '';
					position: absolute;
					left: -32rpx;
					top: 20rpx;
					width: 32rpx;
					height: 2rpx;
					background-color: #1BAE76;
				}
				
				.match-header {
					display: flex;
					align-items: center;
					margin-bottom: 12rpx;
					gap: 16rpx;
					flex-wrap: wrap;
					
					.teams {
						font-size: 30rpx;
						font-weight: 700;
						color: #1d1d1f;
						letter-spacing: 1rpx;
						text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.1);
					}
					
					.venue-info {
						font-size: 26rpx;
						color: #007aff;
						font-weight: 600;
						letter-spacing: 0.5rpx;
						text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.1);
					}
				}
				
				.time-info {
					margin-bottom: 16rpx;
					
					.time-range {
						font-size: 26rpx;
						font-weight: bold;
						color: #1BAE76;
						padding: 4rpx 10rpx;
						background-color: #f0f8ff;
						border-radius: 10rpx;
						border: 1rpx solid #d9d9d9;
					}
				}
				
				.referee-assignments {
					display: flex;
					flex-wrap: wrap;
					gap: 16rpx;
					
					.referee-item {
						background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
						padding: 16rpx 20rpx;
						border-radius: 16rpx;
						border: 2rpx solid #e0e0e0;
						display: flex;
						align-items: center;
						gap: 12rpx;
						box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
						transition: all 0.3s ease;
						
						&:hover {
							transform: translateY(-2rpx);
							box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.12);
						}
						
						&.highlight-user {
							background: linear-gradient(135deg, #fff7e6 0%, #fffbe6 100%);
							border: 3rpx solid #ffa940;
							box-shadow: 0 6rpx 16rpx rgba(255, 169, 64, 0.4);
							
							.referee-name {
								color: #d46b08;
								font-weight: 700;
							}
							
							.referee-position {
								color: #fa8c16;
								font-weight: 600;
							}
						}
						
						.referee-name {
							font-size: 30rpx;
							color: #1d1d1f;
							font-weight: 600;
							letter-spacing: 0.5rpx;
						}
						
						.referee-position {
							font-size: 26rpx;
							color: #007aff;
							font-weight: 500;
							white-space: nowrap;
						}
						
						.phone-container {
							display: flex;
							align-items: center;
							margin-left: 12rpx;
							padding: 8rpx 12rpx;
							background: linear-gradient(135deg, #e6f7ff 0%, #f0f8ff 100%);
							border-radius: 12rpx;
							border: 1rpx solid #91d5ff;
							box-shadow: 0 2rpx 6rpx rgba(0, 122, 255, 0.1);
						}
						
						.referee-phone {
							font-size: 28rpx;
							color: #1BAE76;
							font-family: 'Courier New', monospace;
							font-weight: 700;
							letter-spacing: 1rpx;
							text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.1);
						}
					}
					
					.waiting-assignment {
						width: 100%;
						text-align: center;
						padding: 24rpx;
						background: linear-gradient(135deg, #fff7e6 0%, #fffbe6 100%);
						border-radius: 16rpx;
						border: 2rpx solid #ffd591;
						box-shadow: 0 4rpx 12rpx rgba(255, 213, 145, 0.3);
						
						.waiting-text {
							font-size: 30rpx;
							color: #d46b08;
							font-weight: 600;
							font-style: italic;
							text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.1);
						}
					}
				}
			}
		}
	}
}

.bottom-actions {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	padding: 20rpx 30rpx;
	background-color: #fff;
	border-top: 1rpx solid #e8e8e8;
	box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.1);
	
	.action-btn {
		width: 100%;
		height: 88rpx;
		font-size: 28rpx;
		font-weight: 500;
		border: none;
		border-radius: 44rpx;
		
		&.back-btn {
			background-color: #f5f5f5;
			color: #666;
			border: 2rpx solid #e0e0e0;
			
			&:active {
				background-color: #e8e8e8;
			}
		}
	}
}

// 动画定义已清理
</style> 